package Niuke;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;


//自己写的生产者消费者
//注意 两个人的停顿时间不能一样，或者不写，这样不会交替输出
public class Reentlock2consumer {

    private static int  total=10;

    private static ReentrantLock lock=new ReentrantLock();
    //cosumer
    private static Condition consumer_=lock.newCondition();
    //producer
    private static Condition prouder_ = lock.newCondition();

    static class Consumer extends Thread {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep((int)Math.random()*1000+500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.lock();
                try {
                    while (total == 0) {
                        consumer_.await();
                        System.out.println("cosumer waiting--");
                    }
                    total--;
                    System.out.println("消费了一个，剩余：" + total);
                    prouder_.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }

        }
    }

    static class Produer extends Thread{
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep((int)Math.random()*1000+300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.lock();
                try {
                    while (total >= 10) {
                        prouder_.await();
                        System.out.println("producer waiting--");
                    }
                    total++;
                    System.out.println(Thread.currentThread().getName()+":"+"生产了一个，剩余：" + total);
                    consumer_.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new Produer().start();;
        new Consumer().start();
    }
}
